package com.wngbms;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.jdbc.AtomikosDataSourceBean;

import javax.transaction.UserTransaction;
import java.sql.*;
import java.util.Properties;

public class AtomikosDemo {

    public static AtomikosDataSourceBean atomikosDataSourceBean(String dbName) {
        Properties p = new Properties();
        p.setProperty("url", "jdbc:mysql://localhost:3306/" + dbName);
        p.setProperty("user", "root");
        p.setProperty("password", "password");

        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        ds.setUniqueResourceName(dbName);
        ds.setXaDataSourceClassName("com.mysql.cj.jdbc.MysqlXADataSource");
        ds.setXaProperties(p);
        return ds;
    }

    public static void main(String[] args) {

        AtomikosDataSourceBean ds1 = atomikosDataSourceBean("db_user");
        AtomikosDataSourceBean ds2 = atomikosDataSourceBean("db_account");

        Connection conn1 = null, conn2 = null;
        PreparedStatement ps1 = null, ps2 = null;

        UserTransaction userTransaction = new UserTransactionImp();

        try {
            userTransaction.begin();

            conn1 = ds1.getConnection();
            ps1 = conn1.prepareStatement("INSERT into user(name) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
            ps1.setString(1, "wngbms");
            ps1.executeUpdate();

            ResultSet generatedKeys = ps1.getGeneratedKeys();
            int userId = -1;
            while (generatedKeys.next()) {
                userId = generatedKeys.getInt(1);
            }

//            int i = 1 / 0;

            conn2 = ds2.getConnection();
            ps2 = conn2.prepareStatement("INSERT into account(user_id,money) VALUES (?,?)");
            ps2.setInt(1, userId);
            ps2.setDouble(2, 100000);
            ps2.executeUpdate();

            userTransaction.commit();
        } catch (Exception e) {

            try {
                userTransaction.rollback();
            } catch (Exception systemException) {
                systemException.printStackTrace();
            }

        } finally {

            try {
                if (ps1 != null) {
                    ps1.close();
                }
                if (ps2 != null) {
                    ps2.close();
                }
                if (conn1 != null) {
                    conn1.close();
                }
                if (conn2 != null) {
                    conn2.close();
                }
                ds1.close();
                ds2.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
}
